﻿using System;

namespace ZquenceStudio3Host.DspPlugins.Synthesizers.Nodesizer.Engine.Modules.HighLevel
{
    [ModuleDisplay("Deci")]
    public class DecimalModule : BaseModule
    {
        private double mModMove;
        private double mNextValue;
        private int mModTime;

        public readonly ModuleInput Value;
        public readonly ModuleInput Input;
        public readonly ModuleOutput Output;

        public DecimalModule(ModuleManager manager)
            : base(manager)
        {
            AddInput(Value = new ModuleInput("Dec", IOType.AudioOrWaveform, this));
            AddInput(Input = new ModuleInput("In", "Input", IOType.AudioOrWaveform, this));
            AddOutput(Output = new ModuleOutput("Out", "Output", IOType.AudioOrWaveform, this));
        }

        public override void Process()
        {
            if (Input.IsConnected)
            {
                double[] input = Input.FromOutput.AudioBuffer.Buffer;
                double[] output = Output.AudioBuffer.Buffer;
                
                if (Value.IsConnected)
                {
                    double[] value = Value.FromOutput.AudioBuffer.Buffer;
                    int length = input.Length;
                    for (int i = 0; i < length; ++i, ++mModTime)
                    {
                        int modValue = (int)(value[i] * 50);

                        if (modValue < 1)
                        {
                            modValue = 1;
                        }

                        int modTime = mModTime % modValue;
                        if (modTime == 0)
                        {
                            // Next value.
                            mNextValue = input[i];
                        }
                        mModMove = modTime;

                        output[i] = mNextValue;
                    }
                }
                else
                {
                    Array.Copy(input, output, input.Length);
                }
            }
        }
    }
}
